import Vue from 'vue';
import { State } from './store';

export class BaseVue extends Vue {
    // 获取 store 状态
    public get state() {
        return this.$store.state as State;
    }

    // 获取请求对象
    public get request() {
        return this.$root.$options.request!;
    }

    /**
     * element方法简单封装
     * 解决this定义时element的方法编辑器会报红
     */
    public showMessage(config: any) {
        return this.$message(config);
    }

    public t(transText: string) {
        return this.$t(transText);
    }

    /**
     * 前后端通用请求方法
     */
    public async getBanner() {
        const res = await this.request.get('/b2bbanner', {
            params: {
                code: 'nt',
                lan: 'en'
            }
        });

        this.$store.commit('getBanner', res.data);
    }
    public async getHomeNewsList() {
        const res = await this.request.get('/WebNews/Getlist', {
            params: {
                kind: "news",
                size: 3,
                page: 1
            }
        });

        this.$store.commit('getHomeNewsList', res.data);
    }

    /**
     * 其他
     */

    public signin(name: string) {
        this.$store.commit('signin', name);
    }
    public signout() {
        this.$store.commit('signin', '');
    }

    public async getBlogList() {
        const res = await this.request.get('/api/blog/list');
        if (res.success) {
            this.$store.commit('getBlogList', res.data.list);
        }
    }

    public async postBlog(content: string) {
        const res = await this.request.post('/api/blog', {
            author: this.state.user.name,
            content
        });
        if (res.success) {
            this.getBlogList(); // 发表成功后，重新获取微博数据
            return true;
        }
        alert('发表失败');
        return false;
    }

    public async getCurrentUser() {
        const res = await this.request.get('/api/current-user');
        if (res.success) {
            return this.signin(res.data.name);
        }
    }
}
